// my-products.ts
// 导入API工具
import { saleApi } from '../../utils/api'
Component({
  data: {
    currentTab: 'purchased',
    products: [],
    allProducts: [],
    cart: [],
    totalPrice: 0
  },

  

  lifetimes: {
    attached() {
      this.loadProducts()
    }
  },

  pageLifetimes: {
    show() {
      this.loadProducts()
    }
  },

  methods: {
    loadProducts() {
      if (this.data.currentTab === 'purchased') {
        this.loadPurchasedProducts()
      } else {
        this.loadCartProducts()
      }
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },

    async loadPurchasedProducts() {
      try {
        // 获取用户信息
        const memberInfo = wx.getStorageSync('userInfo')

        // 调用API获取购买记录
        const res = await saleApi.getMyPurchases({ memberId: memberInfo.id })
        console.log('获取购买记录成功:', res)
        
        if (res.code === 200 && res.data) {
          // 格式化购买记录数据
          const products = res.data.records.map((purchase: any) => ({
            id: purchase.productId,
            name: purchase.productName,
            price: purchase.totalAmount,
            quantity: purchase.quantity,
            image: purchase.image || '',
            purchaseDate: purchase.createdAt || purchase.purchaseDate,
            status: purchase.status || 'completed'
          }))

          console.log('格式化购买记录数据:', products)

          this.setData({
            products,
            allProducts: products
          })
        } else {
          wx.showToast({
            title: res.message || '获取购买记录失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取购买记录失败:', error)
        wx.showToast({
          title: '获取购买记录失败',
          icon: 'none'
        })
        
        // 如果API调用失败，回退到本地存储
        const purchaseHistory = wx.getStorageSync('purchaseHistory') || []
        let products = []
        
        purchaseHistory.forEach((purchase: any) => {
          purchase.items.forEach((item: any) => {
            products.push({
              ...item,
              purchaseDate: purchase.date
            })
          })
        })

        this.setData({
          products,
          allProducts: products
        })
      }
    },

    loadCartProducts() {
      const cart = wx.getStorageSync('cart') || []
      
      this.setData({
        products: cart,
        allProducts: cart
      })
      
      this.calculateTotal()
    },

    switchTab(e: any) {
      const tab = e.currentTarget.dataset.tab
      this.setData({ currentTab: tab })
      this.loadProducts()
    },

    calculateTotal() {
      const { products } = this.data
      const totalPrice = products.reduce((sum: number, item: any) => sum + item.price * item.quantity, 0)
      this.setData({ totalPrice })
    },

    increaseQuantity(e: any) {
      const id = parseInt(e.currentTarget.dataset.id)
      const cart = wx.getStorageSync('cart') || []
      
      const item = cart.find((item: any) => item.id === id)
      if (item) {
        item.quantity += 1
        wx.setStorageSync('cart', cart)
        this.loadProducts()
      }
    },

    decreaseQuantity(e: any) {
      const id = parseInt(e.currentTarget.dataset.id)
      const cart = wx.getStorageSync('cart') || []
      
      const item = cart.find((item: any) => item.id === id)
      if (item && item.quantity > 1) {
        item.quantity -= 1
        wx.setStorageSync('cart', cart)
        this.loadProducts()
      }
    },

    deleteFromCart(e: any) {
      const id = parseInt(e.currentTarget.dataset.id)
      
      wx.showModal({
        title: '确认删除',
        content: '确定要从购物车删除这个商品吗？',
        success: (res) => {
          if (res.confirm) {
            const cart = wx.getStorageSync('cart') || []
            const newCart = cart.filter((item: any) => item.id !== id)
            wx.setStorageSync('cart', newCart)
            this.loadProducts()
          }
        }
      })
    },

    goToCheckout() {
      wx.switchTab({
        url: '/pages/cart/cart'
      })
    }
  }
})